package com.zuimei.zuimei.service;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;

import com.zuimei.zuimei.R;
import com.zuimei.zuimei.activities.DownLoadManagerActivity;
import com.zuimei.zuimei.utils.MD5Util;

import org.wlf.filedownloader.DownloadFileInfo;
import org.wlf.filedownloader.FileDownloader;
import org.wlf.filedownloader.listener.OnDetectBigUrlFileListener;
import org.wlf.filedownloader.listener.OnFileDownloadStatusListener;

import java.io.File;
import java.util.HashMap;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

/**
 * Created by Jogger on 2017/1/25.
 * 下载服务
 */

public class DownLoadService extends Service implements OnFileDownloadStatusListener {
    private HashMap<String, String> mLoadMap;
    private NotificationManager mManager;
    private NotificationCompat.Builder mBuilder;
    private String mTitle;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mLoadMap = new HashMap<>();
        // 将当前service注册为FileDownloader下载状态监听器
        FileDownloader.registerDownloadStatusListener(this);
        // 如果希望service启动就开始下载所有未完成的任务，则开启以下实现
        FileDownloader.continueAll(true);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        String action = intent.getAction();
        String url = intent.getStringExtra("url");
        mTitle = intent.getStringExtra("title");
        //准备通知
        mBuilder = new NotificationCompat.Builder(this);
        RemoteViews views = new RemoteViews(getPackageName(), R.layout.download_notify_layout);
        views.setTextViewText(R.id.tv_title, mTitle);//设置属性
        views.setProgressBar(R.id.pb_download, 100, 0, false);
        views.setTextViewText(R.id.tv_cancel, "取消");
        views.setTextViewText(R.id.tv_progress, "0%");
        views.setImageViewResource(R.id.iv_icon_download, R.drawable.icon_download_selector);
        Intent intents = new Intent(this, DownLoadManagerActivity.class);
        intents.putExtra("url",url);
        intents.putExtra("title",mTitle);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intents, PendingIntent
                .FLAG_ONE_SHOT);
        mBuilder.setSmallIcon(R.drawable.icon_download_management_selector)
                .setContentTitle(mTitle)
                .setContentText("下载中")
                .setTicker("下载")
                .setCustomBigContentView(views)//设置通知
                .setContentIntent(pendingIntent);
        mBuilder.setAutoCancel(true);
        ;// 使用setContent()方法添加自定义视图
        mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mManager.notify(1001, mBuilder.build());
        if ("start.action".equals(action)) {
            FileDownloader.detect(url, new OnDetectBigUrlFileListener() {// 创建一个自定义保存路径和文件名称的下载
                @Override
                public void onDetectNewDownloadFile(String url, String fileName, String saveDir,
                                                    long fileSize) {
                    // 如果有必要，可以改变文件名称fileName和下载保存的目录saveDir
                    //FileDownloader.createAndStart(url, newFileDir, newFileName);
                    String newFileDir = Environment.getExternalStorageDirectory()
                            .getAbsolutePath() + File.separator + "Download";
                    String newFileName = MD5Util.MD5(fileName) + ".apk";
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        FileDownloader.createAndStart(url, newFileDir, fileName);
                    } else
                        FileDownloader.createAndStart(url, newFileDir, fileName);
                }

                @Override
                public void onDetectUrlFileExist(String url) {
                    // 继续下载，自动会断点续传（如果服务器无法支持断点续传将从头开始下载）
                    DownloadFileInfo fileInfo = FileDownloader.getDownloadFile(url);
                    File file = new File(fileInfo.getFileDir(), fileInfo.getFileName());
                    if (file.exists()) {
                        FileDownloader.start(url);
                    } else {
                        FileDownloader.reStart(url);//重新下载
                    }
                }

                @Override
                public void onDetectUrlFileFailed(String url, DetectBigUrlFileFailReason
                        failReason) {
                    // 探测一个网络文件失败了，具体查看failReason

                }
            });
            FileDownloader.start(url);// 如果文件没被下载过，将创建并开启下载，否则继续下载，自动会断点续传（如果服务器无法支持断点续传将从头开始下载）
            mLoadMap.put(url, url);
        } else if ("pause.action".equals(action)) {
            FileDownloader.pause(url);
        }

        //mManager.notify(1001, mBuilder.build());
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        // 将当前service取消注册为FileDownloader下载状态监听器
        FileDownloader.unregisterDownloadStatusListener(this);
        // 如果希望service停止就停止所有下载任务，则开启以下实现
        FileDownloader.pauseAll();// 暂停所有下载任务
    }

    @Override
    public void onFileDownloadStatusWaiting(DownloadFileInfo downloadFileInfo) {
        // 发送通知或者广播
    }

    @Override
    public void onFileDownloadStatusPreparing(DownloadFileInfo downloadFileInfo) {
        // 发送通知或者广播
    }

    @Override
    public void onFileDownloadStatusPrepared(DownloadFileInfo downloadFileInfo) {
        // 发送通知或者广播
    }

    @Override
    public void onFileDownloadStatusDownloading(DownloadFileInfo downloadFileInfo, float
            downloadSpeed, long
                                                        remainingTime) {
        // 发送通知或者广播downloadFileInfo.getDownloadedSizeLong():当前下载量
        //获取当前下载进度
        int progress = (int) (((float) downloadFileInfo.getDownloadedSizeLong() /
                downloadFileInfo.getFileSizeLong()) * 100);
        mBuilder.getBigContentView().setProgressBar(R.id.pb_download, 100, progress, false);
        mBuilder.getBigContentView().setTextViewText(R.id.tv_progress, progress + "%");
        mManager.notify(1001, mBuilder.build());

    }

    @Override
    public void onFileDownloadStatusPaused(DownloadFileInfo downloadFileInfo) {
        // 发送通知或者广播
    }

    @Override
    public void onFileDownloadStatusCompleted(DownloadFileInfo downloadFileInfo) {
//        FileDownloader.delete(downloadFileInfo.getUrl(), true, new OnDeleteDownloadFileListener() {
//        });
        // 发送通知或者广播
        mManager.cancel(1001);
        install(downloadFileInfo.getFileDir(), downloadFileInfo.getFileName());
    }

    /**
     * 安装应用程序
     *
     * @param filePath 文件路径
     * @param fileName 文件名
     */
    private void install(String filePath, String fileName) {
        File file = new File(filePath, fileName);
        Uri uri = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }


    @Override
    public void onFileDownloadStatusFailed(String url, DownloadFileInfo downloadFileInfo,
                                           FileDownloadStatusFailReason failReason) {
        // 发送通知或者广播
    }

}
